package com.xxrl.hmwork.controller;

import com.xxrl.hmwork.commons.Jackson;
import com.xxrl.hmwork.commons.StringUtils;
import com.xxrl.hmwork.domain.Homework;
import com.xxrl.hmwork.service.FileService;
import com.xxrl.hmwork.service.HomeworkService;
import com.xxrl.hmwork.vo.FileItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.List;

/**
 * 作业文件的逻辑
 * @author mis
 */
@RestController
@RequestMapping("/file")
public class FileController {

    private static final String DEC_PREFIX = "-";
    private Jackson jackson = Jackson.me();

    private final FileService fileService;
    private final HomeworkService homeworkService;

    @Autowired
    public FileController(FileService fileService
            , HomeworkService homeworkService) {
        this.fileService = fileService;
        this.homeworkService = homeworkService;
    }

    @PostMapping("upload")
    public ResponseEntity<String> upload(String homeworkId
            , @RequestParam(defaultValue = "") String user
            , @RequestParam MultipartFile file) {
        if (StringUtils.isEmpty(homeworkId) ||
                !homeworkService.validate(Long.parseLong(homeworkId)) ||
                file == null) {
            return ResponseEntity.badRequest().body("Error: 表单错误");
        }

        fileService.uploadCloudFile(user,file);
        if (!fileService.upload(homeworkId,file)) {
            return ResponseEntity.accepted().body("Error: 服务器上传失败");
        }
        return ResponseEntity.accepted().body("Ok");
    }

    @GetMapping("download")
    public ResponseEntity<String> download(HttpServletResponse response
            , String fileName) {
        if (fileService.download(response,fileName)) {
            return ResponseEntity.accepted().body("Ok");
        }
        return ResponseEntity.badRequest().body("Error happened");
    }

    /**
     * 打包并下载
     * @param response 响应
     * @param type 前缀
     * @return 返回是否成功
     */
    @GetMapping("downloadZip")
    public ResponseEntity<String> downloadZip(HttpServletResponse response
            , String type) {

        if (fileService.download(response, type,true)) {
            return ResponseEntity.accepted().body("Ok");
        }
        return ResponseEntity.badRequest().body("Error happened");
    }

    /**
     * 将指定前缀的文件 用zip打包 email 发送
     * @param address 邮件地址
     * @param type 作业的id， 即文件的前缀
     * @return 响应
     */
    @PostMapping("emailFile")
    public ResponseEntity<String> emailFile(String address, String type) {

        if (fileService.emailZip(type,address)) {
            return ResponseEntity.accepted().body("Ok");
        }
        return ResponseEntity.badRequest().body("Error happened");
    }

    /**
     * 列出作业
     * @param page 第几页
     * @param limit 每页的大小
     * @param sort 是否降序
     * @param title 文件名 所包含的
     * @param homeworkTitle 作业的标题
     * @return 封装好的数据
     */
    @GetMapping("list")
    public String list(Integer page
            , Integer limit
            , @RequestParam(defaultValue = "") String sort
            , @RequestParam(name = "title", defaultValue = "") String title
            , @RequestParam(name = "type" ,defaultValue = "") String homeworkTitle) {
        List<FileItem> list;

        // 用标题查询作业
        Homework homework = homeworkService.query(homeworkTitle);
        if (homework != null) {
            homeworkTitle = homework.getOid().toString();
        }

        if (StringUtils.isEmpty(homeworkTitle)) {
            homeworkTitle = "";
        }
        list = fileService.listFile(page, limit, title, homeworkTitle);

        if (sort.startsWith(DEC_PREFIX)) {
            Collections.reverse(list);
        }
        int len = fileService.countFile();
        String json = jackson.toJson(list);
        json = "{ \"items\" : " + json +", \"total\":"+len+"}";
        return json;
    }

    /**
     *
     * @param page 第几页
     * @param limit 每页的大小
     * @param deleteFileName 要删除的文件列表的拼接字符串
     * @return 删除完 list文件
     */
    @PostMapping("save")
    public String save(Integer page, Integer limit,@RequestParam(name = "list") String deleteFileName) {
        String[] files;
        // 特殊字符 暂时没找到好的解决方法
        deleteFileName =  deleteFileName.replaceAll("%20"," ");
        if (!StringUtils.isEmpty(deleteFileName)) {
            files = deleteFileName.split(",");
        } else {
            files = new String[0];
        }
        List<FileItem> list = fileService.saveDelete(page, limit, files);
        int len = fileService.countFile();
        String json = jackson.toJson(list);
        json = "{ \"items\" : " + json +", \"total\":"+len+"}";
        return json;
    }
}

